package org.swimv2.servlet;

import java.io.IOException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.controller.GestioneMessaggi;
import org.swimv2.controller.GestioneMessaggiRemote;
import org.swimv2.exception.MessaggioNonValidoException;
import org.swimv2.model.Persona;



public class CreaMessaggioServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	/**
     * @see HttpServlet#HttpServlet()
     */
    public CreaMessaggioServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        Properties props = new Properties();
		props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		Context ctx;
		try{
			
			ctx = new InitialContext(props);
			Object obj = ctx.lookup(GestioneMessaggi.JNDI_NAME);
			GestioneMessaggiRemote manager = (GestioneMessaggiRemote)PortableRemoteObject.narrow(obj,GestioneMessaggiRemote.class);
			
			String dest = request.getParameter("destinatario");
			String titolo = request.getParameter("titolo");
			String corpo =request.getParameter("messaggio");
			
			RequestDispatcher disp = null;
			Persona u = (Persona) request.getSession().getAttribute("utente");
			String mitt=u.getUserID();
			
			try{
				
				
				manager.nuovoMessaggio(mitt, dest, titolo, corpo);
				disp = request.getRequestDispatcher("WEB-INF/messaggi.jsp");
				
			}
			catch(MessaggioNonValidoException e){
				request.setAttribute("messaggio", e.getErrore());
			}
			
			disp.forward(request, response);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}
	

}
